import crypto from 'crypto';
const config = {
  SECRET_KEY: 'zoNE32byteexamplekeyforaes256gcm', // 密钥，必须是32个字节长度
  IV: 'gcmIVSE@4c8d', // 随机向量，长度为12字节
};

// 加密函数
function encrypt(data) {
  const cipher = crypto.createCipheriv('aes-256-gcm', config.SECRET_KEY, config.IV);
  const encrypted = cipher.update(data, 'utf8', 'base64') + cipher.final('base64');

  // 获取认证标记
  const tag = cipher.getAuthTag();

  // 将密文和认证标记合并为一个数组
  const result = new Uint8Array(config.IV.length + Buffer.from(encrypted, 'base64').byteLength + tag.byteLength);
  result.set(Buffer.from(encrypted, 'base64'), config.IV.length);
  result.set(tag, config.IV.length + Buffer.from(encrypted, 'base64').byteLength);

  // 将字节数组转换成Base64编码的字符串
  return btoa(String.fromCharCode(...result));
}

// 解密函数
function decrypt(data) {
  // 将Base64编码的字符串转换成字节数组
  const dataArray = new Uint8Array(atob(data).split('').map((c) => c.charCodeAt(0)));

  // 将12字节后剩余的字节作为密文和认证标记
  const ciphertextWithTag = dataArray.slice(12);
  const ciphertext = ciphertextWithTag.slice(0, ciphertextWithTag.byteLength - 16);
  const tag = ciphertextWithTag.slice(ciphertextWithTag.byteLength - 16);

  // 初始化解密器，并设置认证标记
  const decipher = crypto.createDecipheriv('aes-256-gcm', config.SECRET_KEY, config.IV);
  decipher.setAuthTag(tag);

  // 使用解密算法进行解密
  return decipher.update(Buffer.from(ciphertext), 'binary', 'utf8') + decipher.final('utf8');
}

export default {
  decrypt,
  encrypt
};
